package com.example.yangxu0703.thundermapclient.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.yangxu0703.thundermapclient.R;
import com.example.yangxu0703.thundermapclient.interaction.HoldByDialog;
import com.example.yangxu0703.thundermapclient.util.Util;
import com.thundersoft.mm.phone.ConnectionManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.PriorityQueue;

public class SelectContactActivity extends BaseActivity implements View.OnClickListener {
    public ArrayList<String> all_res;
    public List<String> sendList;
    public ArrayList<String> choose;
    public ListView listView;
    private TextView back, operation, info;
    public HoldByDialog holdByDialog;
    public ArrayList<Boolean> check_status = new ArrayList<>();
    private ContactAdapter adapter;
    private SharedPreferences sharedPreferences;
    private ArrayList<Boolean> contactMode=new ArrayList<>();

    private String TAG = "SelectContactActivity";
    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (all_res.size() == 0) {
                info.setVisibility(View.VISIBLE);
                operation.setVisibility(View.GONE);
                listView.setVisibility(View.GONE);
            } else {
                for (String s : all_res) {
                    int i = 0;

                    if (sendList != null && sendList.get(i) != null && sendList.contains(s)) {
                        check_status.add(true);
                        i++;
                    } else {
                        check_status.add(false);
                    }
                }
                Log.i("TAG",""+check_status);
                adapter = new ContactAdapter(all_res, check_status,contactMode);
                listView.setAdapter(adapter);
                Log.i(TAG, all_res.size() + "--");
            }
            holdByDialog.dismiss();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_contact);
        contactMode.add(0,false);
        listView = findViewById(R.id.list_contact);
        back = findViewById(R.id.back_user);
        back.setOnClickListener(this);
        operation = findViewById(R.id.operation);
        operation.setOnClickListener(this);
        info = findViewById(R.id.info_contact);
        all_res = new ArrayList<>();
        choose = new ArrayList<>();
        //获取发送联系人的状态
        sharedPreferences = getSharedPreferences("Contact", MODE_PRIVATE);
        String glassContact = sharedPreferences.getString("GlassContact", "");
        Log.i("TAG", glassContact + "String");
        if (glassContact != null) {
            String[] glass = glassContact.split("-");
            sendList = Arrays.asList(glass);
        }
        choose.addAll(sendList);

        initAdapter();
        holdByDialog = new HoldByDialog(this);
        holdByDialog.showDialog("正在加载....");
        new Thread() {
            @Override
            public void run() {
                super.run();
                all_res = getContacts();
                all_res = Util.removeDuplicate(all_res);
                handler.sendEmptyMessage(0);
            }
        }.start();

    }

    private void initAdapter() {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i(TAG, "" + check_status.get(position));
                if (contactMode.get(0)) {
                    if (check_status.get(position)) {
                        check_status.remove(position);
                        check_status.add(position, false);
                        choose.remove(all_res.get(position));
                    } else {
                        if (choose.size() < 10) {
                            check_status.remove(position);
                            check_status.add(position, true);
                            if (!choose.contains(all_res.get(position))){
                                choose.add(all_res.get(position));
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private ArrayList<String> getContacts() {
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME};
        ArrayList<String> Allinfo = new ArrayList<>();
        Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
        String[] arr = new String[cursor.getCount()];
        int i = 0;
        if (cursor != null && cursor.moveToFirst()) {
            do {
                Long id = cursor.getLong(0);
                String name = cursor.getString(1);
                String[] phoneProjection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER};
                String tem = name;
                Cursor phonesCusor = this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, phoneProjection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
                if (phonesCusor != null && phonesCusor.moveToFirst()) {
                    do {
                        String num = phonesCusor.getString(0);
                        tem = num + "=" + tem + ";";
                        if (tem.split(";").length > 3) {
                            continue;
                        }
                        tem.trim();
                        Allinfo.add(tem);
                    } while (phonesCusor.moveToNext());
                }
                i++;
            } while (cursor.moveToNext());
        }
        return Allinfo;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.operation:
                if (contactMode.get(0)){
                    contactMode.set(0,false);
                    operation.setText("选择");
                    adapter.notifyDataSetChanged();
                    //确认发送
                    Log.i("TAG", "--------------" + choose.size());
                    ConnectionManager.sendPhoneNumber(choose);
                    String tem = "";
                    for (String s : choose) {
                        if (s==null) continue;
                        tem = s + "-" + tem;
                    }
                    Log.i("TAG", "-----" + tem);
                    if (!tem.equals("")){
                        tem.substring(0,tem.lastIndexOf(";"));
                    }
                    //save the sended contect people!
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString("GlassContact", tem);
                    edit.commit();
                    SelectContactActivity.this.finish();
                    //返回取消
                }else {
                    contactMode.set(0,true);
                    operation.setText("发送");
                    adapter.notifyDataSetChanged();
                }
                break;
            case R.id.back_user:
                startActivity(new Intent(SelectContactActivity.this, UserCenterActivity.class));
                SelectContactActivity.this.finish();
                break;
        }
    }

    private class ContactAdapter extends BaseAdapter {
        ViewHold viewHold = null;
        ArrayList<String> arrayList;
        ArrayList<Boolean> status;
        ArrayList<Boolean> mode;

        public ContactAdapter(ArrayList<String> arrayList, ArrayList<Boolean> status, ArrayList<Boolean> mode) {
            this.arrayList = arrayList;
            this.status = status;
            this.mode=mode;
        }

        @Override
        public int getCount() {
            return arrayList.size();
        }

        @Override
        public Object getItem(int position) {
            return arrayList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            return super.isEnabled(position);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                viewHold = new ViewHold();
                convertView = LayoutInflater.from(SelectContactActivity.this).inflate(R.layout.item_contact_form, null, false);
                viewHold.name = convertView.findViewById(R.id.connect_name);
                viewHold.number = convertView.findViewById(R.id.connect_number);
                viewHold.status = convertView.findViewById(R.id.check_send);
                convertView.setTag(viewHold);
            } else {
                viewHold = (ViewHold) convertView.getTag();
            }
            viewHold.number.setText(arrayList.get(position).split("=")[0]);
            viewHold.name.setText(arrayList.get(position).split("=")[1].split(";")[0]);
            if (mode.get(0)) {
                if (status.get(position)) {
                    viewHold.status.setBackground(getResources().getDrawable(R.drawable.choosed_icon));
                } else {
                    viewHold.status.setBackground(getResources().getDrawable(R.drawable.cycle));
                }
            }else {
                if (status.get(position)) {
                    viewHold.status.setBackground(getResources().getDrawable(R.drawable.choosed_icon));
                } else {
                    viewHold.status.setBackground(null);
                }
            }
            return convertView;
        }

        public class ViewHold {
            public TextView name, number;
            public TextView status;
        }
    }


}
